package com.hfi.anemicVsdomain.ddd;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.Money;

import java.math.RoundingMode;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * @author ChangLiang
 * @date 2020/5/18
 */
@AllArgsConstructor
@Slf4j
public class ThreeWayRecognitionStrategy implements RecognitionStrategy {

    private int firstOffset;

    private int secondOffset;

    @Override
    public void calculateRevenueRecognition(Contract contract) {
        Money temp = contract.getRevenue().dividedBy(3, RoundingMode.UNNECESSARY);
        contract.addRevenueRecognition(
                RevenueRecognition.builder()
                        .contractId(contract.getId())
                        .amount(temp)
                        .recognizedDate(contract.getSignedDate())
                        .build());
        log.info("contractId: {}, money: {}， recognitionDate: {}", contract.getId(), temp.toString(), contract.getSignedDate());
        doAddRevenueRecognition(contract, temp, firstOffset);
        doAddRevenueRecognition(contract, temp, secondOffset);
    }

    private void doAddRevenueRecognition(Contract contract, Money temp, int firstOffset) {
        contract.addRevenueRecognition(
                RevenueRecognition.builder()
                        .contractId(contract.getId())
                        .amount(temp)
                        .recognizedDate(Date.from(
                                Instant.ofEpochMilli(contract.getSignedDate().getTime())
                                        .plus(firstOffset, ChronoUnit.DAYS)))
                        .build());
        log.info("contractId: {}, money: {}， recognitionDate: {}", contract.getId(), temp.toString(), Date.from(
                Instant.ofEpochMilli(contract.getSignedDate().getTime())
                        .plus(firstOffset, ChronoUnit.DAYS)));
    }
}
